import {getAction} from '@/api/manage'
import YchConstant from "@/api/YchConstant";
import store from '@/store'

const invalidChars = /[^a-zA-Z0-9:]+/g

export default {
  refreshLocale() {
    // getAction(YchConstant.PREFIX_EFORM + '/manage/localeProvider/getLocales').then((res) => {
    //   store.commit("SET_LOCALE", res.result)
    // })
  },
  getLocale(key) {
    if (!key) {
      return key
    }
    if (key.startsWith("m.")) {
      // 加载完成前，window.$vm还未赋值，可能是空
      if (window.$vm) {
        return window.$vm.$t(key)
      } else if (window.$i18n) {
        return window.$i18n.t(key)
      } else {
        return key;
      }
    }
    return store.getters.locale[key] || key
  },
  containsLocaleKey(key) {
    if (!key) {
      return false
    }
    if (key.startsWith("m.")) {
      return true
    }
    return store.getters.locale.hasOwnProperty(key)
  },
  getTableColCode(tableName, colName, name) {
    if (!tableName || !colName) {
      return name
    }
    // 如果禁用了切换语言，则直接使用原文返回
    if(!bootConfig[process.env.NODE_ENV].VUE_APP_LOCALE_ENABLE){
      return name
    }
    const key = tableName + "_" + this.snakeCase(colName);
    if (this.containsLocaleKey(key)) {
      return key
    }
    return name
  },
  snakeCase(str) {
    return str
      .replace(/[A-Z]/g, match => '_' + match)
      .replace(/([^a-zA-Z])_([A-Z])/g, match => match[0] + match[2])
      .replace(/^_/, '')
      .replace(invalidChars, '_')
      .toLowerCase()
  }
}
